package cn.edu.sdjzu.xg.controller;

import cn.edu.sdjzu.xg.domain.School;
import cn.edu.sdjzu.xg.service.SchoolService;
import cn.edu.sdjzu.xg.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/schoolUpdate.ctl")
public class SchoolUpdateController extends HttpServlet {
    //修改
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        JSONObject respMessage_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        String request_jsonStr = JSONUtil.getJSON(request);
        JSONObject request_jsonObj = JSON.parseObject(request_jsonStr);
        if (request_jsonObj == null) {
            respMessage_jsonObj.put("message", "未收到请求信息");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        try {
            School school = JSON.parseObject(request_jsonStr,School.class);
            responseEditTeacher(school, response);
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            e.printStackTrace();
            response.getWriter().println(respMessage_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            e.printStackTrace();
            response.getWriter().println(respMessage_jsonObj);
            e.printStackTrace();
        }
    }
    private void responseEditTeacher(School school, HttpServletResponse response) throws IOException,SQLException {
        boolean edit = SchoolService.getInstance().update(school);
        JSONObject resp_jsonObj = new JSONObject();
        if (edit) {
            resp_jsonObj.put("message", "修改成功");
        }else {
            resp_jsonObj.put("message", "修改失败");
        }
        response.getWriter().println(resp_jsonObj);
    }
}
